Lesson 5 - if statements

If statements have three main parts. These are shown in the code example below. Notice that the true and false blocks are indented. This is how python knows that code belongs inside the true or false block. The expression and the else must be followed by a : (colon).

  1. conditional expression
  2. true block of code
  3. false block of code

x = 5
if x > 3: # expression
	print "x is bigger than 3" # true block
else:
	print "x is smaller than 3" # false block


If you fail to indent then the code will not work as indended. The code block below shows how things can go wrong. The first version has failed to indent a print statement. As such it will run regardless of the outcome of the expression. In the second version both print statements are considered part of the if statement and as such will not print.


x = 10
# this code prints x is very small. it should not print this!
if x < 5:
	print "x is less than 5"
print "x is very small!!"
# this is the correct version
if x < 5:
	print "x is less than 5"
	print "x is very small!!"


It is possible to do more than one test in the same if statement. This is known as else if, or elif in python. This can be seen practically in the example below. This is a snippet from a secret number guessing game. Here we want to let the user know if they were close or not. You can download secretv1.py here. the elif code must be followed by a conditional expression.


guess = 43
secret = 21
if guess > secret:
	print "guess is too big"
elif guess < secret:
	print "guess is too small"
else:
	print "Well done you guessed correctly!"


key learning points